package com.symaster.gameengine.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;

/**
 * @author yinmiao
 * @since 2024/9/15
 */
public class ImageRendererUtil {

    public static ByteBuffer getByteBuffer(String filename) {
        try (FileInputStream inputStream = new FileInputStream(filename);) {
            return readImageToByteBuffer(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static ByteBuffer readImageToByteBuffer(InputStream inputStream) throws IOException {
        // 读取 InputStream 到 ByteBuffer
        try (var channel = Channels.newChannel(inputStream)) {
            ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); // 预先分配一个 16KB 的缓冲区
            int bytesRead;
            while ((bytesRead = channel.read(buffer)) != -1) {
                if (buffer.remaining() == 0) {
                    // 如果缓冲区已满，扩展缓冲区大小
                    ByteBuffer newBuffer = ByteBuffer.allocateDirect(buffer.capacity() * 2);
                    buffer.flip();
                    newBuffer.put(buffer);
                    buffer = newBuffer;
                }
            }
            buffer.flip();
            return buffer;
        }
    }
}
